package com.gecolin.geekweek2;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

public class HttpClientDemo {
    /**
     *  post 请求
     */
    public static String doPost(String urlString, String param,Map<String,String> headerMap) {
        // 创建返回对象
        StringBuilder result = new StringBuilder();

        URL url = null;
        try {
            url = new URL(urlString);
            URLConnection connection = url.openConnection();
            HttpURLConnection httpconn = (HttpURLConnection) connection;

            // 设置允许输入输出 请求类型
            httpconn.setDoOutput(true);
            httpconn.setDoInput(true);
            httpconn.setUseCaches(false);
            httpconn.setRequestMethod("POST");
            // 设置请求头
            httpconn.setRequestProperty("accept","*/*");
            httpconn.setRequestProperty("connection", "Keep-Alive");
            httpconn.setRequestProperty("Charset", "UTF-8");
            httpconn.setRequestProperty("Accept-Charset", "UTF-8");
            httpconn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            if(headerMap != null){
                for(Iterator<String> iter = headerMap.keySet().iterator(); iter.hasNext();){
                    String key = iter.next();
                    String value = headerMap.get(key);

                    httpconn.setRequestProperty(key,value);
                }
            }
            // 打开连接
            httpconn.connect();

            // 获取输出流 传递参数
            OutputStreamWriter out = new OutputStreamWriter(httpconn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();
            out.close();

            // 获取输入流 获取返回的数据
            InputStream in = httpconn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            in.close();
            // 关闭连接
            httpconn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
        return result.toString();
    }
    public static void main(String[] args) throws Exception {

        String url = "http://localhost:8801";
        String text = HttpClientDemo.doPost(url,"",null);
        System.out.println("url: " + url + " ; response: \n" + text);

    }
}
